import 'dart:io';

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:wallet_utils/color.dart';
import 'package:wallet_utils/photo_view/view.dart';
import 'package:wallet_utils/report_widget/click_widget.dart';
import 'package:wallet_utils/report_widget/default_network_image.dart';
import 'package:wallet_utils/text_util.dart';
import 'package:image_picker/image_picker.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../permissions_utils.dart';
import '../toast.dart';

/// @author: pengboboer
/// @createDate: 2021/12/29
class ImageGridWidget extends StatefulWidget {
  final String? title;
  final int maxCount;
  final List<String>? initImgList;
  final ValueChanged<List<String>>? onChanged;
  final bool isEdit;

  const ImageGridWidget(
      {Key? key,
      this.title,
      this.maxCount = 9,
      this.initImgList,
      this.onChanged,
      this.isEdit = true})
      : super(key: key);

  @override
  State<ImageGridWidget> createState() => _ImageGridWidgetState();
}

class _ImageGridWidgetState extends State<ImageGridWidget> {
  late List<String> _imgPathList;

  @override
  void initState() {
    super.initState();
    _imgPathList = widget.initImgList ?? [];
  }

  @override
  void didUpdateWidget(covariant ImageGridWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    _imgPathList = widget.initImgList ?? [];
  }

  @override
  Widget build(BuildContext context) {
    bool lastItemIsAddBtn = _imgPathList.length < widget.maxCount;
    return RepaintBoundary(
      child: Container(
        color: ColorManager.colorFFFFFF,
        padding: EdgeInsets.symmetric(horizontal: 8.w, vertical: 12.w),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Visibility(
              visible: !TextUtil.isEmpty(widget.title),
              child: Padding(
                padding: EdgeInsets.only(top: 8.w, bottom: 5.w, left: 8.0.w),
                child: Text(
                  widget.title ?? "",
                  style: TextStyle(
                    fontSize: 15.sp,
                    color: ColorManager.color_4D4D4D,
                  ),
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                ),
              ),
            ),
            GridView.builder(
              padding: EdgeInsets.zero,
              shrinkWrap: true,
              physics: const NeverScrollableScrollPhysics(),
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                  crossAxisCount: 3,
                  mainAxisSpacing: 6.w,
                  crossAxisSpacing: 6.w),
              itemCount: lastItemIsAddBtn && widget.isEdit
                  ? _imgPathList.length + 1
                  : _imgPathList.length,
              itemBuilder: (BuildContext context, int index) {
                return lastItemIsAddBtn &&
                        index == _imgPathList.length &&
                        widget.isEdit
                    ? _buildAddItem()
                    : _buildItem(index);
              },
            )
          ],
        ),
      ),
    );
  }

  Widget _buildItem(int index) {
    return Stack(
      children: [
        ClickWidget(
          onTap: () {
            PhotoViewPage.start(_imgPathList, index: index);
          },
          child: Container(
            padding: EdgeInsets.all(8.w),
            width: double.infinity,
            height: double.infinity,
            child: ClipRRect(
                borderRadius: BorderRadius.circular(4.w),
                child: DefaultNetworkImage(_imgPathList[index])),
          ),
        ),
        Positioned(
          right: 0,
          top: 0,
          child: Visibility(
            visible: widget.isEdit,
            child: ClickWidget(
              onTap: () {
                FocusScope.of(context).requestFocus(FocusNode());
                _imgPathList.removeAt(index);
                setState(() {});
                widget.onChanged?.call(_imgPathList);
              },
              child: Padding(
                padding: EdgeInsets.only(left: 12.w, bottom: 12.w),
                child: Image.asset("images/circle_gray_delete.png",
                    package: "hopson_utils",
                    width: 16.w,
                    height: 16.w,
                    fit: BoxFit.cover),
              ),
            ),
          ),
        )
      ],
    );
  }

  Widget _buildAddItem() {
    return ClickWidget(
      onTap: _onClickAdd,
      child: Container(
        padding: EdgeInsets.all(8.w),
        width: double.infinity,
        height: double.infinity,
        child: ClipRRect(
            borderRadius: BorderRadius.circular(4.w),
            child: Image.asset("images/img_add_icon.png",
                package: "hopson_utils", fit: BoxFit.cover)),
      ),
    );
  }

  void _onClickAdd() async {
    FocusScope.of(context).requestFocus(FocusNode());
    if (!await PermissionsUtils.isPhotoPermissionGranted()) {
      ToastUtils.showToast("请在设置中开启${Platform.isAndroid ? "存储" : "相册"}权限");
      return;
    }
    List<AssetEntity>? images = await AssetPicker.pickAssets(
      context,
      themeColor: ColorManager.colorF65247,
      maxAssets: widget.maxCount - _imgPathList.length,
      // gridCount: 3,
      // pageSize: 120,
      requestType: RequestType.image,
      specialItemPosition: SpecialItemPosition.prepend,
      specialItemBuilder: (BuildContext context) {
        return GestureDetector(
          behavior: HitTestBehavior.opaque,
          onTap: () async {
            if (!await PermissionsUtils.isCameraPermissionGranted()) {
              ToastUtils.showToast("请在设置中开启相机权限");
              return;
            }
            final XFile? file =
                await ImagePicker().pickImage(source: ImageSource.camera);
            if (file != null && !TextUtil.isEmpty(file.path)) {
              AssetEntity result = AssetEntity(
                  id: '',
                  typeInt: 1,
                  width: 0,
                  height: 0,
                  relativePath: file.path);
              Navigator.of(context).pop(<AssetEntity>[result]);
            }
          },
          child: const Center(
            child: Icon(Icons.camera_enhance, size: 42.0),
          ),
        );
      },
    );
    _handleImages(images);
  }

  void _handleImages(List<AssetEntity>? images) async {
    if (images?.isEmpty ?? true) {
      return;
    }
    for (var entity in images!) {
      // id为空代表是camera拍照
      if (TextUtil.isEmpty(entity.id)) {
        _imgPathList.add(entity.relativePath!);
        break;
      }
      final File? originFile = await entity.originFile;
      if (!TextUtil.isEmpty(originFile?.path)) {
        _imgPathList.add(originFile!.path);
      }
    }
    setState(() {});
    widget.onChanged?.call(_imgPathList);
  }
}

bool isAllItemIsHttpString(List<String>? list) {
  if (list?.isEmpty ?? true) return false;
  for (var element in list!) {
    if (!element.startsWith("http")) return false;
  }
  return true;
}
